package errorview;

import java.util.Map;

import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class ErrorBean {

	private static final String BR = "n";
	private boolean showStackTrace;
	private String errorDetails;
	private String errorTitle = "";
	
	@PostConstruct
	public void start() {
		showStackTrace = false;
		errorDetails = "";
		setErrorTitle("");
	}

	public String getStackTrace() {
		if (errorDetails.equals("")) {
			FacesContext context = FacesContext.getCurrentInstance();
			Map<String, Object> map = context.getExternalContext().getRequestMap();
			Throwable throwable = (Throwable) map
					.get("javax.servlet.error.exception");
			StringBuilder builder = new StringBuilder();
			builder.append(throwable.getMessage()).append(BR);
			for (StackTraceElement element : throwable.getStackTrace()) {
				builder.append(element).append(BR);
			}
			this.errorDetails = builder.toString();
			return builder.toString();
		} else {
			return this.errorDetails;
		}
	}

	public static String getBr() {
		return BR;
	}

	public void viewStack() {
		if (showStackTrace) {
			showStackTrace = false;
		} else {
			showStackTrace = true;
		}
	}

	public void setShowStackTrace(boolean showStackTrace) {
		this.showStackTrace = showStackTrace;
	}

	public void something(AjaxBehaviorEvent ev) {
		viewStack();
	}

	public boolean isShowStackTrace() {
		return showStackTrace;
	}

	public void setErrorDetails(String errorDetails) {
		this.errorDetails = errorDetails;
	}

	public String getErrorDetails() {
		return errorDetails;
	}

	public void setErrorTitle(String errorTitle) {
		if (!errorTitle.equals("")) {
			this.errorTitle = errorTitle;
		}
	}

	public String getErrorTitle() {
		return errorTitle;
	}
}
